﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

using Fungus;

public class TalkPressF : MonoBehaviour
{

    //public static TalkPressF Instance; 


    [Header("可以对话的对象")]
   public GameObject[] CanTalkGameObject;
    [Header("Fungus的Flowchart对象")]
    public Flowchart flowchart;

    public bool isDongTalk ;

    public bool canPressFtalk;
  

    public void NotDoingTalk()
    {
        isDongTalk = false;
    }

    public void IsDoingTalk()
    {
        isDongTalk = true;
    }


    // Use this for initialization
    void Start()
    {
        StartCoroutine(FindCanTalkGameObject());

        canPressFtalk = true;
        isDongTalk = false;
        Find_FlowChat();
      //  CanTalkGameObject = GameObject.FindGameObjectsWithTag("CanTalkObject");
      // GameEventSystemMain.Load_A_NewSceneDone += CheckNewSceneLoad;

        //  GameEventSystemMain.EnablePressFTalk += EnablePressFTalk;

        // GameEventSystemMain.DisablePressFTalk += DisablePressFTalk;
    }
    
    void Find_FlowChat()
    {
        try
        {
            flowchart = GameObject.Find("MainFlowchart").GetComponent<Flowchart>();
        }
        catch
        {
            Debug.Log("未找到Flowchart对象");
        }
    }

    void CheckNewSceneLoad()
    {
        // CanTalkGameObject = GameObject.FindGameObjectsWithTag("CanTalkObject");
        StartCoroutine(FindCanTalkGameObject());

    }

    IEnumerator FindCanTalkGameObject()
    {
        CanTalkGameObject = null;
        yield return new WaitForSeconds(0.2f);
        CanTalkGameObject = GameObject.FindGameObjectsWithTag("CanTalkObject");
        yield return new WaitForSeconds(0.5f);
        Debug.Log("找到的可对话NPC数量：" + CanTalkGameObject.Length);
    }

   
    public float fireTime = 0F;    //第一次按键--时间
    public float coolTime = 1.5F;   //间隔冷却时间

    //无用方法，，暂时没有使用
    void Set_Currer_Time()
    {
        if (fireTime < coolTime)
        {
            fireTime += Time.deltaTime;
            //当fireTime小于coolTime 的时候  firetime开始增加到fireTime
           // Debug.Log(fireTime);
        }
        if (fireTime > coolTime)
        {
            fireTime = coolTime;
        }
    }
    
    void PressFKey()
    {
       
        if (canPressFtalk)
        {
            //Set_Currer_Time();
            if (Input.GetKeyUp(KeyCode.F) )//&& fireTime == coolTime )
            {

               // Check_Call_Talk();
               // fireTime = 0;
            }
        }
    }

    public void EnablePressFTalk()
    {
        canPressFtalk = true;
    }

    public void DisablePressFTalk()
    {
        canPressFtalk = false;
    }

   

    public void Check_Call_Talk()
    {
        if (GetCanTalkObjectTalkKey() != "")
        {
            string talk_sendmessage = GetCanTalkObjectTalkKey();
            //获取id
            // if (alltalks.Count == 0)
            if (flowchart != null)
            {
                try
                {


                    // flowchart.SetBooleanVariable(talk_bool_keyvalue, true);

                    flowchart.SendFungusMessage(talk_sendmessage);

                    Debug.Log("开始执行--谈话动作......");
                    ////禁止玩家移动
                    //发送转换玩家，，正在谈话的状态
                   // PlayerGameStage stage = PlayerGameStage.IsDoingTalk;
                  //  EventMsgHelper.SendEvent(GameEventString.OnPlayerGameStageChange, this, GameHashKeyString.PlayerGameStageOneValue, stage);
                }
                catch
                {
                    Debug.LogError("对话失败，，发生了某种错误......");
                }
                //this.GetComponent<PlayerMove>().DisablePlayerMove();
            }

          
        }
        else
        {
            Debug.Log("为空-无法触发对话或距离NPC太远了");
        }
    }

    /// <summary>
    /// 返回数据要查找的-关键对话key-npc对象的名字
    /// </summary>
    /// <returns></returns>
    public string GetCanTalkObjectTalkKey()
    {
        if (CheckOneObjectCanTalk() == null)
        {
            return "";
        }
        else
        {
            return CheckOneObjectCanTalk().talk_message_key;
        }
    }

    public CanTalkObjectItem CheckOneObjectCanTalk()
    {
        CanTalkObjectItem coo = null;

        if ( CanTalkGameObject != null &&  CanTalkGameObject.Length != 0 )
        {

            for(int index = 0; index < CanTalkGameObject.Length; index++)
            {
                if (CheckPlayerNpcDistance(CanTalkGameObject[index].transform))
                {
                    coo = CanTalkGameObject[index].GetComponent<CanTalkObjectItem>();
                    break;
                }
            }
            //foreach (GameObject co in CanTalkGameObject)
            //{
            //    if (CheckPlayerNpcDistance(co.transform))
            //    {
            //        coo = co.GetComponent<CanTalkObjectItem>();
            //        break;
            //    }
            //}
            return coo;
        }
        else
        {
            return null;
        }

    }

    Vector2 playerpox;
    Vector2 npcpox;
    /// <summary>
    /// 检查某个对象-跟当前玩家的距离
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    bool CheckPlayerNpcDistance(Transform obj)
    {
         playerpox = new Vector2(this.transform.position.x, this.transform.position.y);
         npcpox = new Vector2(obj.transform.position.x, obj.transform.position.y);
        //谈话距离参数
       // Debug.Log("面对-当前谈话对象的距离："+ Vector2.Distance(playerpox, npcpox).ToString() );
        if (Vector2.Distance(playerpox, npcpox) < 0.8f)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}
